package it.tukano.fun;

/**
 * A function that converts a type into another one
 * @author pgi
 * @param <OUT>
 * @param <IN>
 */
public class Cast<IN, OUT> implements Function1<IN, OUT> {

    /** The conversion type */
    private final Class<OUT> type;

    /**
     * Instance initializer
     */
    public Cast(Class<OUT> type) {
        this.type = type;
    }

    /**
     * Cast the p element to V type if compatibile
     * @param p the value to cast
     * @return the result of the conversion or null if the type is not convertible
     */
    public OUT apply(IN p) {
        return type.isAssignableFrom(p.getClass()) ? type.cast(p) : null;
    }
}
